#include <stddef.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#ifdef WIN32
#include <io.h>
#endif
#include "n2base.h"
#include "n2x86asm.h"



#ifdef WIN32

void dumpAllToken(TAsxTokenTab* tokens);                    //temp debug use 

extern "C" int wmain(int argc, wchar_t** argv);

int wmain(int argc, wchar_t** argv)
{
    if (libn2base_init() < 0)
        return -1;
    x86as_init_multilanguage();

    if (argc==1) {
        x86AsmShowHelp();
        exit(0);
    }
    if (argc==2 && ((0==wcscmp(argv[1], L"-h")) || 
        (0==wcscmp(argv[1], L"--help")) || (0==wcscmp(argv[1], L"-help") )))
    {
        x86AsmShowHelp();
        exit(0);
    }

    srand((unsigned)time(NULL));
    SetAssembleActionSSID();

    //if (is_little_endian())
    //    macIsLittle = true;
    //else
    //    macIsLittle = false;

    if (argc < 2) {
        n2print("need args\n");
        exit(2);
    }

    try
    {
        TPreproedSrc * SrcPieces;
        SrcPieces = new TPreproedSrc;
        if (SrcPieces == NULL)
            throw AsxEx_NoMemory;
        PreProcessSourceFile(SrcPieces, argc, argv);

        TAsxTokenTab * tokens;
        tokens = new TAsxTokenTab;
        tokens->PrepareDivideTokens(SrcPieces);
        tokens->DoDivideTokens();
        tokens->FinishDivideTokens();

        delete SrcPieces;

        dumpAllToken(tokens);

        AssemblePreprocessedSource(tokens);


        delete tokens;
        TAsxSymbol::FreeSymbolTabStringPool();
    }
    catch (EBaseLibExp* e)
    {
    	
    }
    catch (TEAsxExp* e)
    {
    }

}

void dumpAllToken(TAsxTokenTab* tokens)
{
    FILE * fpout;

    fpout = _wfopen(L"TokenTable.txt", L"wt");
    if ( fpout==NULL )
    {
        n2print("open file error. \n");
        exit(1);
    }

    TAsxTokenLine* line = tokens->head;
    while (line)
    {
        fprintf(fpout, "==========================================================================================================\n");
        fprintf(fpout, "%s\n", line->GetStr());
        TAsxToken * tks;
        tks = line->head;
        int count = 1;
        while (tks) {
            const char * tkstr;
            fprintf(fpout, "%06d    ", count);
            tkstr = tks->GetStr();
            if (tkstr[0]=='\n' && tkstr[1]==0)
                fprintf(fpout, "\\n");
            else
                fprintf(fpout, "%s", tkstr);
            fprintf(fpout, "\n");
            tks = tks->next;
            count++;
        }


        line = line->next;
    }


    fclose(fpout);
}

#else

int main(int argc, char** argv)
{

}

#endif //WIN32



